package cn.zxf.note.note.review;

import cn.zxf.note.common.jpa.EntityRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import jakarta.transaction.Transactional;
import java.util.List;

import static cn.zxf.note.note.review.NoteReviewStatusEnum.*;

public interface NoteReviewRepository extends EntityRepository<NoteReview> {

    default int countByNoteId(Integer noteId) {
        return this.countByNoteIdAndStatus(noteId, List.of(INITIAL.code, REVIEWED.code));
    }

    @Query("SELECT COUNT(*) FROM NoteReview WHERE noteId = :note_id AND status IN :status_list")
    int countByNoteIdAndStatus(
            @Param("note_id") Integer noteId,
            @Param("status_list") List<Integer> statusList
    );


    default void deleteByNoteId(Integer noteId) {
        this.changeStatusByNoteId(noteId, INITIAL.code, DELETED.code);
    }

    @Transactional
    @Modifying
    @Query("UPDATE NoteReview SET status = :to WHERE noteId = :note_id AND status = :from")
    void changeStatusByNoteId(
            @Param("note_id") Integer noteId,
            @Param("from") Integer fromStatus,
            @Param("to") Integer toStatus
    );

}
